package Homework;

//字符串实现的加密算法 参考教材P204
public class PassString {
    public static void main(String[] args) {
        String content = "今年冬天呼吸道疾病增多，注意安全";
        String key = "安全";
        String dest = encrypt(content, key);
        System.out.println(dest);
        String source = decrypt(dest, key);
        System.out.println(source);
    }

    // 加密
    static String encrypt(String source, String key) {
        char[] p = key.toCharArray();
        int n = p.length;
        char[] c = source.toCharArray();
        int m = c.length;

        for(int k=0;k<m;k++){
            int mima = c[k] + p[k%n];
            c[k] = (char) mima;
        }
        return new String(c);
    }

    // 解密
    static String decrypt(String source, String key) {
        char[] p = key.toCharArray();
        int n = p.length;
        char[] c = source.toCharArray();
        int m = c.length;

        for(int k=0;k<m;k++){
            int mima = c[k] - p[k%n];
            c[k] = (char) mima;
        }
        return new String(c);
    }
}
